<template>
  <div class="TextInput w-full select-none bg-c-white">
    <p class="heading-s-medium text-c-grey-3xl pb-2">
      {{ label }}
    </p>
    <div
      class="flex border rounded-lg px-4 py-3 max-h-12 hover:border-c-grey-large"
      :class="inputComputedClasses"
    >
      <AtomInput
        ref="focusTarget"
        :type="inputTypeState"
        :placeholder="placeholder"
        :value="modelValue"
        @input="updateValue"
      />
      <SvgoPasswordShow
        v-if="showPasswordShowIcon"
        class="cursor-pointer stroke-c-grey-medium hover:stroke-c-grey-large"
        filled
        @click="togglePasswordVisibility"
      />
      <SvgoPasswordUnshow
        v-if="showPasswordUnshowIcon"
        class="cursor-pointer text-c-grey-medium hover:text-c-grey-large"
        filled
        @click="togglePasswordVisibility"
      />
    </div>
    <p v-show="error" class="label-s-medium text-c-accent-red-m pt-2">
      {{ errLabel }}
    </p>
  </div>
</template>

<script setup lang="ts">
interface Props {
  label: string
  placeholder: string
  errLabel?: string
  type?: 'text' | 'password'
  modelValue: string
  error?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  label: 'Input',
  placeholder: 'Input something',
  errLabel: 'error',
  error: false,
  type: 'text',
  modelValue: ''
})
const emit = defineEmits(['update:modelValue'])
const { label, placeholder, errLabel, error, type, modelValue } = toRefs(props)
const inputTypeState: Ref<'password' | 'text'> = ref(type.value)
const focusTarget = ref()
const { focused } = useFocus(focusTarget)

const showPasswordShowIcon = computed(
  () => type.value === 'password' && inputTypeState.value === 'password'
)
const showPasswordUnshowIcon = computed(
  () => type.value === 'password' && inputTypeState.value === 'text'
)
const inputComputedClasses = computed(() => ({
  'border-c-accent-red-m': error.value && !focused.value,
  'border-c-grey-xs': !error.value && !focused.value,
  'border-c-grey-large': focused.value
}))

const updateValue = (e: Event) => {
  emit('update:modelValue', (e.target as HTMLInputElement).value)
}

const togglePasswordVisibility = () => {
  inputTypeState.value === 'password'
    ? (inputTypeState.value = 'text')
    : (inputTypeState.value = 'password')
}
</script>

<style lang="scss" scoped>
$component: '.TextInput';
</style>
